package com.banciyuan.bcywebview.biz.main.message.messagedetail;

import android.os.Bundle;
import android.view.View;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.MessageApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.MessageBroadCast;

/**
 * Created by squall on 2016/4/1.
 */
public class MessageBroadCastActivity extends BaseActivity {

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private ListView mListView;
    private PullToRefreshListView mRefreshList;
    private MessageBroadCastAdapter messageBroadCastAdapter;
    private List<MessageBroadCast> messageList = new ArrayList<MessageBroadCast>();


    private RequestQueue mQueue;
    private int page = 1;
    private boolean is_load = false;
    private boolean is_end = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_list);
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initData();
        initAction();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initAction() {
        mRefreshList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                is_load = false;
                is_end = false;
                page = 1;
                initData();
            }
        });

        mRefreshList.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!is_load && !is_end) {
                    is_load = true;
                    page++;
                    initData();
                }
            }
        });
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.broadcast));
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi() {
        mRefreshList = (PullToRefreshListView) findViewById(R.id.topic_refresh_lv);
        mListView = mRefreshList.getRefreshableView();
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + MessageApi.getMessageAnnounce();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, MessageBroadCastActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        List<MessageBroadCast> temp = gson.fromJson(result, new TypeToken<List<MessageBroadCast>>() {
                        }.getType());
                        if (temp.size() == 0) {
                            is_end = true;
                        }
                        renderData(temp);
                        notifyMessageUpdate();
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                    mRefreshList.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
                mRefreshList.onRefreshComplete();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        mQueue.add(stringRequestParam);
    }

    private void notifyMessageUpdate() {
        if (page == 1) {
            FlagUtils.ifAnnounce = false;
        }
    }

    private void renderData(List<MessageBroadCast> temp) {
        if (page == 1) {
            messageList.clear();
        }
        messageList.addAll(temp);
        if (messageBroadCastAdapter == null) {
            messageBroadCastAdapter = new MessageBroadCastAdapter(this, messageList);
            mListView.setAdapter(messageBroadCastAdapter);
        } else {
            messageBroadCastAdapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
        mRefreshList.onRefreshComplete();
        is_load = false;
    }


}
